package com.fyyg.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Locale;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;

import com.fyyg.common.util.date.DateUtil;


public class FileOperationUtil {
	
	private static final Logger log = Logger.getLogger(FileOperationUtil.class);
	
	public static void main(String[]args) throws IOException{
		/*System.out.println(getFileSuffix("sfs.aa.aa.txt"));
		System.out.println(deleteFile("c:\\test.gif"));
		System.out.println(renameFile("d:/abc.txt", "e:/1.txt"));
		System.out.println(readTextFromFile("d:/abc.txt","gbk"));
		saveFile(new FileInputStream(new File("d:/abc.txt")), "d:/wwwww.txt");
		System.out.println(getFilesizeInfo(new File("d:/Jellyfish.jpg")));
		
		 byte[] byteArray=readFileToByte("d:/wwwww.txt");
		 writeFileFromByte(byteArray, "d:/aaassa.txt");*/
		long a=System.currentTimeMillis();
		//copyFile("c:/test.jpg", "c:/www/cc.jpg");
		System.out.println(new File("c:/test.jpg").getAbsolutePath());
		System.out.println("耗时:"+(System.currentTimeMillis()-a)+"ms");
	}
	
	
	
	/**
	 * 计算文件大小，返回文件大小字符串
	 * @param file
	 * @return
	 * 小于1k的，显示为1kB
	 * 大于1k，小于1M的，显示**KB
	 * 大于1M,小于1G的，显示**MB
	 * 大于1G的，显示**GB
	 */
	public static String getFilesizeInfo(File file){
		if (file.isFile()&&file.exists()) {
			long size=file.length();
		    DecimalFormat df = new DecimalFormat("#.00");
		    String fileSizeString = "";
		    if (size < 1024) {
		    	fileSizeString="1KB";
		    } else if (size < 1048576) {
		           fileSizeString =  df.format((double) size / 1024) + "KB";
		    } else if (size < 1073741824) {
		            fileSizeString = df.format((double) size / 1048576) + "MB";
		    } else {
		            fileSizeString = df.format((double) size / 1073741824) + "GB";
		    }
		        return fileSizeString;
		}else {
			return null;
		}
	}
	/**
	 * 把文件流保存到指定位置
	 * @param in
	 * @param path
	 * @throws IOException 
	 */
	public static void saveFile(InputStream is,String path) throws IOException{
		FileUtils.copyInputStreamToFile(is, new File(path));
	}
	
	
	/**
	 * 下载文件，如果文件不存在，报错
	 * @param path 文件路径
	 * bool true表示成功，false表示失败
	 */
	public static boolean downloadFile(HttpServletResponse response,String filepath,String fileName){
		boolean bool = false;
		PrintWriter pw = null;
		File file=new File(filepath);
		if (!file.exists()) {
			return false;
		}
		try {
			InputStream is = new FileInputStream(file);
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1" ));
			response.setContentType("application/x-download;");
			pw = response.getWriter();
			int i;    
			while ((i=is.read()) != -1)   {    
				 pw.write(i);    
			}    
			is.close();
			bool = true;//表示执行成功
		} catch (IOException e) {
			log.error(e);
		}finally{
			pw.close(); 
		}
		return bool;
	}
	
	
	
	/**
	 * 将文件读入byte数组
	 * @param path 文件路径
	 * @return
	 * @throws FileNotFoundException 
	 */
	public static byte[] readFileToByte(String path)  throws IOException{
		BufferedInputStream bufferedInputStream = new BufferedInputStream(
				new FileInputStream(path));
		int len = bufferedInputStream.available();
		byte[] bytes = new byte[len];
		int r = bufferedInputStream.read(bytes);
		if (len != r) {
			bytes = null;
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}
	
	
	/**
	 * 将byte数组存成文件
	 * @param array
	 * @param path
	 * @return true表示写入成功，false表示写入失败
	 */
	public static boolean writeFileFromByte(byte[] array,String path){
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		boolean result = true;
		try {
			file=new File(path);
			File parent = file.getParentFile();
			if(parent!=null&&!parent.exists()){
				parent.mkdirs();
			} 
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(array);
		} catch (Exception e) {
			result = false;
			log.error(e);
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					log.error(e1);
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					log.error(e1);
				}
			}
		}
		return result;
	}
	
	
	/**
	 * 删除文件
	 * 如果文件不存在，返回true
	 * 如果文件存在，且是文件，返回删除结果；如果不是文件，直接返回false
	 * @param path 文件路径
	 */
	public static boolean deleteFile(String path){
		File file=new File(path);
		//文件是否存在
		if (file.exists()) {
			if (file.isFile()) { //如果是文件
				return file.delete(); 
			}
			return false;
		}else {
			//文件已经删除，返回true
			return true;
		}
		
	}
	
	
	/**
	 * 取得文件的后缀名
	 * @param path 文件全路径，或者是文件名
	 * @return
	 */
	public static String  getFileSuffix(String path){
		 return FilenameUtils.getExtension(path).toLowerCase(
					Locale.ENGLISH);
	}
	
	
	
	/**
	 * 给文件重命名或者移动文件
	 * @param orginal 源文件文件地址
	 * @param target  目标文件地址
	 * @return
	 *当原文件不存在时，返回false
	 *如果重命名后的文件已经存在，返回false，否则返回true
	 */
	public static boolean renameFile(String orginal,String target){
		File orginalFile=new File(orginal);
		if (orginalFile.exists()) {
			return orginalFile.renameTo(new File(target));
		}else {
			return false;
		}
	}
	
	
	/**
	 * 复制文件
	 * @param source
	 * @param target
	 * @return
	 */
	public  static boolean copyFile(String source, String target) {  
	    InputStream fis = null;  
	    OutputStream fos = null;  
	    try {  
	    	File destFile=new File(target);
	    	File parentFile=destFile.getParentFile();
	    	if (parentFile!=null&&!parentFile.exists()) {
				parentFile.mkdirs();
			}
	        fis = new BufferedInputStream(new FileInputStream(source));  
	        fos = new BufferedOutputStream(new FileOutputStream(target));  
	        byte[] buf = new byte[1024*5];  
	        int i;  
	        while ((i = fis.read(buf)) != -1) {  
	            fos.write(buf, 0, i);  
	        } 
	        fis.close();
	        fos.close();
	        return true;
	    }  
	    catch (Exception e) {  
	        e.printStackTrace(); 
	    } 
	    return false;
	}  
	
	/**
	 * 将文件读入字符串
	 * @param path 源文件地址
	 * @return
	 * @throws IOException 
	 */
	public static String  readTextFromFile(String path,String encode) throws IOException{
		StringBuffer buffer = new StringBuffer();
		File file = new File(path);
		InputStreamReader read = new InputStreamReader(new FileInputStream(
				file), encode);
		BufferedReader ins = new BufferedReader(read);
		String dataLine = "";
		while (null != (dataLine = ins.readLine())) {
			buffer.append(dataLine);
		}
		ins.close();
		return buffer.toString();
	}
	
	/**
	 * 重新命名文件名
	 * @param name
	 * @return
	 */
	public static String getNewName(String name){
		if(name!=null && !"".equals(name)){
			String lastname = name.substring(name.lastIndexOf("."),name.length());
	        StringBuffer  newname = new StringBuffer(StrUtil.getUUID());
	        newname.append(lastname);
	        return newname.toString();
		}
		return "";
	}
}

